package com.jm.framework.common.result;

import com.jm.framework.common.exception.BaseResultCodeEnum;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.apache.skywalking.apm.toolkit.trace.TraceContext;

/**
 * tide
 * <p>
 * 响应结果
 * <p>
 * author: jiangjianmin
 * <p>
 * create: 2024-08-22 14:18
 **/
@Setter
@Getter
@ToString
@Builder
@NoArgsConstructor
public class BaseResult<T> {
    @ApiModelProperty("结果码")
    private String code;
    @ApiModelProperty("结果信息")
    private String message;
    @ApiModelProperty("链路id")
    private String traceId;
    @ApiModelProperty("返回数据内容")
    private T data;

    public BaseResult(String code, String message) {
        this.code = code;
        this.message = message;
        this.setTraceId();
    }

    public BaseResult(IResultCode resultCode) {
        this(resultCode.getCode(), resultCode.getMessage());
    }

    public BaseResult(IResultCode resultCode, T data) {
        this(resultCode);
        this.data = data;
    }

    public static <T> BaseResult<T> success(T data) {
        return new BaseResult<>(BaseResultCodeEnum.SUCCESS, data);
    }

    public static <T> BaseResult<T> success() {
        return new BaseResult<>(BaseResultCodeEnum.SUCCESS);
    }


    public static BaseResult<Void> fail(IResultCode resultCode, String detailErrorMsg) {
        return new BaseResult<>(resultCode.getCode(), resultCode.getMessage() + "：" + detailErrorMsg);
    }

    public static <T> BaseResult<T> fail(IResultCode resultCode) {
        return new BaseResult<>(resultCode.getCode(), resultCode.getMessage());
    }

    public static <T> BaseResult<T> fail(String code, String message) {
        return new BaseResult<>(code, message);
    }

    @Trace
    public void setTraceId() {
        this.traceId = TraceContext.traceId();
    }
}
